package com.wjc.server.service;


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wjc.server.dto.SectionDto;
import com.wjc.server.dto.SectionPageDto;
import com.wjc.server.entity.Section;
import com.wjc.server.entity.SectionExample;
import com.wjc.server.mapper.SectionMapper;
import com.wjc.server.util.CopyUtil;
import com.wjc.server.util.SnowFlake;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;


@Service
public class SectionService {
    @Resource
    private SectionMapper sectionMapper;

    @Resource
    private CourseService courseService;

    @Resource
    private SnowFlake snowFlake;

    //查询
    public void list(SectionPageDto sectionPageDto){
        PageHelper.startPage(sectionPageDto.getPage(),sectionPageDto.getSize());
        SectionExample sectionExample = new SectionExample();
        SectionExample.Criteria criteria = sectionExample.createCriteria();

        //若chapterid不为空，则按照chapterid查询
        if(!ObjectUtils.isEmpty(sectionPageDto.getChapterId())){
            criteria.andChapterIdEqualTo(sectionPageDto.getChapterId());
        }

        List<Section> sectionList= sectionMapper.selectByExample(sectionExample);
        PageInfo<Section> pageInfo=new PageInfo<>(sectionList);
        sectionPageDto.setTotal(pageInfo.getTotal());

        List<SectionDto> sectionDtosList = CopyUtil.copyList(sectionList,SectionDto.class);
        sectionPageDto.setList(sectionDtosList);

    }

    //保存
    @Transactional
    public void save(SectionDto sectionDto){
            Date now =new Date();

        Section section=CopyUtil.copy(sectionDto,Section.class);
        if (ObjectUtils.isEmpty(section.getId())){
            //新增
                section.setCreatedAt(now);
                section.setUpdatedAt(now);
                section.setId(snowFlake.nextId());
                sectionMapper.insert(section);
        }else {
            section.setUpdatedAt(now);
            sectionMapper.updateByPrimaryKey(section);
        }
        //更新视频时长
        courseService.updateVideoTime(section.getCourseId());

    }

    public void delete(Long id){
        sectionMapper.deleteByPrimaryKey(id);
    }

    /**
     * 查询某一课程下的所有节
     */
    public List<SectionDto> listByCourse(Long courseId) {
        SectionExample example = new SectionExample();
        example.createCriteria().andCourseIdEqualTo(courseId);
        List<Section> sectionList = sectionMapper.selectByExample(example);
        List<SectionDto> sectionDtoList = CopyUtil.copyList(sectionList, SectionDto.class);
        return sectionDtoList;
    }
}
